<?php

namespace app\admin\controller;

use app\admin\model\Admin;
use app\admin\model\CentralcontactProgress;
use app\common\controller\Backend;
use app\admin\model\Fields;
use think\Db;
use fast\Random;
use app\admin\library\Time;
use think\Model;
use think\Request;
use Exception;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Centralcontact extends \app\common\controller\Project
{

    /**
     * Centralcontact模型对象
     * @var \app\admin\model\Centralcontact
     */
    protected $noNeedLogin = ['test','lastestprogress'];
    protected $model = null;
    protected $tablename = 'centralcontact';
    protected $tmpFields = [];
    protected $tmpFieldNames = [];
    protected $fieldNames = [];
    protected $relationtTable = 'progress';
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Centralcontact;
        // $this->relationtTable = 'progress';
        $this->assignconfig('isSuperAdmin',$this->auth->isSuperAdmin());
        $this->assign('isSuperAdmin',$this->auth->isSuperAdmin());
        if($this->auth->isSuperAdmin())
            $this->pre = '';
        else
            $this->pre = 'tmp_';
        $this->assign('pre',$this->pre);

        $this -> tmpFields = [
            'tmp_name',
            'tmp_investment_total',
            'tmp_summary',
            'tmp_progression',
            'tmp_next_measure',
            'tmp_problem',
            'tmp_access_time',
            'tmp_sign_time',
            'tmp_register_time',
            'tmp_chargedep_ids',
            'tmp_chargedep_names',
            'tmp_settle_street_ids',
            'tmp_settle_street_names',
            'tmp_receive_time',
            'tmp_leader_ids',
            'tmp_leader_names',
            'tmp_centraloffice_id',
            'tmp_centraloffice_name',
            'tmp_investment_area',
            'tmp_state',
            'tmp_stop_reason',
            'tmp_stop_time',
            'tmp_framework_agreement_time',
            'tmp_invesment_agreement_time',
            'tmp_start_construction_time',
            'tmp_operation_time',
            'tmp_contact_name',
        ];

        $this -> tmpFieldNames = [
            'tmp_name'  => '项目名称',
            'tmp_investment_total' => '总投资',
            'tmp_summary' => '项目简介',
            'tmp_progression' => '项目进展',
            'tmp_next_measure' => '下一步措施',
            'tmp_problem' => '遇到问题',
            'tmp_access_time' => '计划准入时间',
            'tmp_sign_time' => '计划签约时间',
            'tmp_register_time' => '计划注册时间',
            'tmp_chargedep_ids' => '提报部门IDS',
            'tmp_chargedep_names' => '提报部门名称',
            'tmp_settle_street_ids' => '落户街道IDS',
            'tmp_settle_street_names' => '落户街道名称',
            'tmp_receive_time' => '接洽时间',
            'tmp_leader_ids' => '领导IDS',
            'tmp_leader_names' => '领导名称',
            'tmp_centraloffice_id' => '科室ID',
            'tmp_centraloffice_name' => '科室名称',
            'tmp_investment_area'   => '投资方地区',
            'tmp_state'     => '项目状态',
            'tmp_stop_reason'   => '终止原因',
            'tmp_stop_time' => '终止时间',
            'tmp_framework_agreement_time'  => '签订框架协议时间',
            'tmp_invesment_agreement_time'  => '签订正式投资协议时间',
            'tmp_start_construction_time'   => '开工时间',
            'tmp_operation_time'            => '运营时间',
            'tmp_contact_name'              => '科室责任人'
        ];

        $this -> fieldNames = [
            'name'  => '项目名称',
            'investment_total' => '总投资',
            'summary' => '项目简介',
            'progression' => '项目进展',
            'next_measure' => '下一步措施',
            'problem' => '遇到问题',
            'access_time' => '计划准入时间',
            'sign_time' => '计划签约时间',
            'register_time' => '计划注册时间',
            'chargedep_ids' => '提报部门IDS',
            'chargedep_names' => '提报部门名称',
            'settle_street_ids' => '落户街道IDS',
            'settle_street_names' => '落户街道名称',
            'receive_time' => '接洽时间',
            'leader_ids' => '领导IDS',
            'leader_names' => '领导名称',
            'centraloffice_id' => '科室ID',
            'centraloffice_name' => '科室名称',
            'investment_area'   => '投资方地区',
            'state' => '进展状态',
            'stop_reason'   => '停止时间',
            'stop_time' => '终止时间',
            'framework_agreement_time'  => '签订框架协议时间',
            'invesment_agreement_time'  => '签订正式投资协议时间',
            'start_construction_time'   => '开工时间',
            'operation_time'            => '运营时间',
            'contact_name'              => '科室责任人'
        ];
        $this->whereExtend['is_delete'] = 0;
    }
    public function leader(){
        $admin_id = input('ids');
        // $pids = AdminProject::where(['uid'=>$admin_id])->column('project_id');
        // $where = ['id'=>['in',$pids]];
        $this->whereExtend[] = ['exp',Db::raw("FIND_IN_SET($admin_id,leader_ids)")];
        $this->assignconfig('ids',$admin_id);
        return self::index();
    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            list($tablewhere) = $this->buildtablewhere();

            $total = $this->model
                // ->with($this->relationtTable)
                ->where($where)
                ->where($this->whereExtend)
                ->order($sort, $order)
                ->group('name')
                ->count();

            $tmpSql = Db::name('centralcontact')
                -> order('receive_time desc')
//                ->where($where)
//                ->where($this->whereExtend)
                ->limit(999999) // 不加limit不生效
                -> buildSql();

            $tmp = \db() -> table($tmpSql . " a")
                ->where($tablewhere)
                ->where($this->whereExtend)
                // ->where('receive_time_desc','between time',['2020-12-01 00:00:00','2021-02-08'])
//                ->limit($offset, $limit)  //取消掉limit，获取所有的记录
                ->order($this->sortExtend)
                ->order($sort, $order)
                ->group('a.name')
                ->column('id');

           // echo \db() -> table($tmpSql . " a") -> getLastSql();


            $list = $this->model
                ->with($this->relationtTable)
                ->whereIn('id',$tmp)
                // ->order('id','desc')
                -> order('receive_time desc')
                ->select();
            // pr($list);
            $list = collection($list)->toArray();


            /**
             * 处理审核
             * 获取到所有的记录之后，处理status，然后按照status进行排序
             */

            $names = [];
            foreach ($list as $item) {
                // pr($item->progress);
                $names[] = $item['name'];
            }

            $checkList = $this -> model ->with($this->relationtTable) -> whereIn('name',$names) -> where('status',100) -> select();
            $checkArr = [];
            foreach ($checkList as $k => $v){
                $checkArr[$v['name']] = 1;
            }


            $pendingCheck = [];
            foreach ($list as $k => $v){
                if($v['name'] == ''){
                    unset($list[$k]);
                    continue;
                }
                if(isset($checkArr[$v['name']])){
                    $pendingCheck[] = $v;
                    unset($list[$k]);
                }
            }
            // echo $this->relationtTable;
            $newList = $this -> model->with($this->relationtTable) -> whereNull('name') -> select();
            $newList = collection($newList) -> toArray();
            // echo $this -> model->getLastSql();
            $list = array_merge($newList,$pendingCheck,$list);
            $list = array_slice($list,$offset,$limit);

            foreach ($list as $k => &$v){

                $v['status'] = isset($checkArr[$v['name']]) ? '100' : $v['status'];
                $v['is_remind'] = $this -> auth -> isSuperAdmin() ? $v['is_remind'] : 0;
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        $str = '';
        if(false){
            $time1 = strtotime("-0 year -1 month -0 day");

            $records = $this -> model -> query("select
        -- 总接洽次数
        	sum( IF ( find_in_set( 1, centraloffice_id ), 1, 0 ) ) AS allcount1,
            sum( IF ( find_in_set( 2, centraloffice_id ), 1, 0 ) ) AS allcount2,
            sum( IF ( find_in_set( 3, centraloffice_id ), 1, 0 ) ) AS allcount3,
            sum( IF ( find_in_set( 4, centraloffice_id ), 1, 0 ) ) AS allcount4,
            sum( IF ( find_in_set( 5, centraloffice_id ), 1, 0 ) ) AS allcount5,
            sum( IF ( find_in_set( 6, centraloffice_id ), 1, 0 ) ) AS allcount6,
            sum( IF ( find_in_set( 7, centraloffice_id ), 1, 0 ) ) AS allcount7,
            sum( IF ( find_in_set( 8, centraloffice_id ), 1, 0 ) ) AS allcount8,
        -- 新项目接洽次数
            sum( IF ( find_in_set( 1, centraloffice_id ) && is_new=1, 1, 0 ) ) AS newcount1,
            sum( IF ( find_in_set( 2, centraloffice_id ) && is_new=1, 1, 0 ) ) AS newcount2,
            sum( IF ( find_in_set( 3, centraloffice_id ) && is_new=1, 1, 0 ) ) AS newcount3,
            sum( IF ( find_in_set( 4, centraloffice_id ) && is_new=1, 1, 0 ) ) AS newcount4,
            sum( IF ( find_in_set( 5, centraloffice_id ) && is_new=1, 1, 0 ) ) AS newcount5,
            sum( IF ( find_in_set( 6, centraloffice_id ) && is_new=1, 1, 0 ) ) AS newcount6,
            sum( IF ( find_in_set( 7, centraloffice_id ) && is_new=1, 1, 0 ) ) AS newcount7,
            sum( IF ( find_in_set( 8, centraloffice_id ) && is_new=1, 1, 0 ) ) AS newcount8
        from nsig_centralcontact where create_time between ".$time1." and ".time());
            $records = $records[0];

            //接洽项目数
            $contacts = $this -> model -> query("select
             count(*) as allcount,count(distinct (`name`)) as contactcount
            , (select count(DISTINCT `name`) from nsig_centralcontact where find_in_set( 1, centraloffice_id ) and create_time between ".$time1." and ".time().") as contact1
            , (select count(DISTINCT `name`) from nsig_centralcontact where find_in_set( 2, centraloffice_id ) and create_time between ".$time1." and ".time().") as contact2
            , (select count(DISTINCT `name`) from nsig_centralcontact where find_in_set( 3, centraloffice_id ) and create_time between ".$time1." and ".time().") as contact3
            , (select count(DISTINCT `name`) from nsig_centralcontact where find_in_set( 4, centraloffice_id ) and create_time between ".$time1." and ".time().") as contact4
            , (select count(DISTINCT `name`) from nsig_centralcontact where find_in_set( 5, centraloffice_id ) and create_time between ".$time1." and ".time().") as contact5
            , (select count(DISTINCT `name`) from nsig_centralcontact where find_in_set( 6, centraloffice_id ) and create_time between ".$time1." and ".time().") as contact6
            , (select count(DISTINCT `name`) from nsig_centralcontact where find_in_set( 7, centraloffice_id ) and create_time between ".$time1." and ".time().") as contact7
            , (select count(DISTINCT `name`) from nsig_centralcontact where find_in_set( 8, centraloffice_id ) and create_time between ".$time1." and ".time().") as contact8
           -- , (select count(DISTINCT `name`) from nsig_centralcontact where find_in_set( 1, centraloffice_id ) and is_new=1 and create_time between ".$time1." and ".time().") as newcontact1
           -- , (select count(DISTINCT `name`) from nsig_centralcontact where find_in_set( 2, centraloffice_id ) and is_new=1 and create_time between ".$time1." and ".time().") as newcontact2
           -- , (select count(DISTINCT `name`) from nsig_centralcontact where find_in_set( 3, centraloffice_id ) and is_new=1 and create_time between ".$time1." and ".time().") as newcontact3
           -- , (select count(DISTINCT `name`) from nsig_centralcontact where find_in_set( 4, centraloffice_id ) and is_new=1 and create_time between ".$time1." and ".time().") as newcontact4
           -- , (select count(DISTINCT `name`) from nsig_centralcontact where find_in_set( 5, centraloffice_id ) and is_new=1 and create_time between ".$time1." and ".time().") as newcontact5
           -- , (select count(DISTINCT `name`) from nsig_centralcontact where find_in_set( 6, centraloffice_id ) and is_new=1 and create_time between ".$time1." and ".time().") as newcontact6
           -- , (select count(DISTINCT `name`) from nsig_centralcontact where find_in_set( 7, centraloffice_id ) and is_new=1 and create_time between ".$time1." and ".time().") as newcontact7
           -- , (select count(DISTINCT `name`) from nsig_centralcontact where find_in_set( 8, centraloffice_id ) and is_new=1 and create_time between ".$time1." and ".time().") as newcontact8
            from nsig_centralcontact where create_time between ".$time1." and ".time());
            $contacts = $contacts[0];
            $date1 = date("Y-m-d",$time1);
            $date2 = date("Y-m-d",time());
            $str = <<<EOS
{$date1}至{$date2}，中心共接洽项目{$contacts['contactcount']}个{$contacts['allcount']}次。<br />
招商一科共接洽项目{$contacts['contact1']}个{$records['allcount1']}次，其中接洽新项目{$records['newcount1']}个{$records['newcount1']}次；<br />
招商二科共接洽项目{$contacts['contact2']}个{$records['allcount2']}次，其中接洽新项目{$records['newcount2']}个{$records['newcount2']}次；<br />
招商三科共接洽项目{$contacts['contact3']}个{$records['allcount3']}次，其中接洽新项目{$records['newcount3']}个{$records['newcount3']}次；<br />
招商四科共接洽项目{$contacts['contact4']}个{$records['allcount4']}次，其中接洽新项目{$records['newcount4']}个{$records['newcount4']}次；<br />
招商五科共接洽项目{$contacts['contact5']}个{$records['allcount5']}次，其中接洽新项目{$records['newcount5']}个{$records['newcount5']}次；<br />
招商六科共接洽项目{$contacts['contact6']}个{$records['allcount6']}次，其中接洽新项目{$records['newcount6']}个{$records['newcount6']}次；<br />
办公室共接洽项目{$contacts['contact7']}个{$records['allcount7']}次，其中接洽新项目{$records['newcount7']}个{$records['newcount7']}次；<br />
产业发展科共接洽项目{$contacts['contact8']}个{$records['allcount8']}次，其中接洽新项目{$records['newcount8']}个{$records['newcount8']}次；
EOS;
        }


        $this -> assign('str',$str);
//        $this -> assign('str',$str);
        return $this->view->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }

                $isRecord = isset($params['record']) && $params['record'] == 1 ? true : false;

                // 非管理员需要经过审核
                $insertData = [];
                if(!$this -> auth -> isSuperAdmin()){
                    foreach ($params as $k => &$v) {
//                        if($k == 'name') {
//                            $insertData['name'] = $v;
//                        }

                        $insertData['tmp_'.$k] = $v;
                        unset($params[$k]);
                    }
                    $insertData['status'] = 100;
                    $params = $insertData ?? $params;

                }

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    $id = $this -> model -> getLastInsID();

                    //写入接洽记录
//                    if($isRecord){
//                        $isSupperAdmin = $this -> auth -> isSuperAdmin();
//                        $recordData = [
//                            'centraloffice_id'  => $isSupperAdmin ? $params['centraloffice_id'] : $params['tmp_centraloffice_id'],
//                            'centralcontact_id' => $id,
//                            'centralcontact_name'   => $params['name'],
//                            'leader_ids'    => $isSupperAdmin ? $params['leader_ids'] : $params['tmp_leader_ids'],
//                            'receive_time'  => strtotime($isSupperAdmin ? $params['receive_time'] : $params['tmp_receive_time']),
//                            'is_new'        => 1
//                        ];
//
//                        (new \app\admin\model\Centralcontactrecords()) -> save($recordData);
//                    }
                    //写入日志
                    $logData = [];
                    $row = $this -> model -> find($id);
                    foreach ($this -> tmpFieldNames as $k => $v) {
                        $k = $this -> auth -> isSuperAdmin() ? $this -> ltrim($k) : $k;
                        if(isset($row -> $k) && $row -> $k){
                            $logData[] = [
                                'centralcontact_id' => $id,
                                'admin_id'  => $this -> auth -> id,
                                'field' => $k,
                                'field_name' => $v,
                                'new_value' => $row -> $k,
                                'status' => 300,
                                'info'  => '项目创建',
                                'create_time' => time(),
                                'update_time'   => time()
                            ];
                        }
                    }
                    Db::name('centralcontactlog') -> insertAll($logData);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $chargeDepsArr = \app\admin\model\Chargedep::all();
        $chargeDeps = [];
        foreach ($chargeDepsArr as $dep){
            $chargeDeps[$dep -> id] = $dep -> name;
        }
        $this -> assign('centraloffices',getSelectList('centraloffice'));
        $this -> assign('streets',['-100'=>'待定']+getSelectList('chargedep',['group_id' => 5]));
        $this -> assign('leaders',getSelectList('leader')+['-100' => '无']);
        $this -> assign('chargeDeps',['-100'=>'待定']+$chargeDeps);
        return $this->view->fetch();
    }

    public function edit($ids = NULL) {
        if(!$ids) $this -> error('请重试');
        $row = $this -> model -> find($ids);

        $chargeDepsArr = \app\admin\model\Chargedep::all();
        $chargeDeps = [];
        foreach ($chargeDepsArr as $dep){
            $chargeDeps[$dep -> id] = $dep -> name;
        }

        if($this -> request -> isPost()){
            $data = $this -> request -> post('row/a');
            $updateData = [];
            $logData = [];
            foreach ($data as $k => $v) {
                if($data[$k] == PENDING)
                    $data[$k] = PENDING_TEXT;
                if(isset($row -> $k) && $row -> $k != (is_array($data[$k]) ? implode(',',$data[$k]) : $data[$k])){
                    if(is_int($row -> $k) && (substr($k,-5) == '_time') && date("Y-m-d",$row -> $k) == $data[$k]) continue;
                    $key = $this -> auth -> isSuperAdmin() ? $k : 'tmp_'.$k;
                    // var_dump($row->$k);
                    // var_dump($data[$k]);
                    $updateData[$key] = $data[$k];
                    $logData[] = [
                        'centralcontact_id' => $row -> id,
                        'admin_id'  => $this -> auth -> id,
                        'field' => $k,
                        'field_name' => $this -> tmpFieldNames[$k] ?? ($this -> fieldNames[$k] ?? ''),
                        'ori_value' => $row -> $k,
                        'new_value' => is_array($data[$k]) ? implode(',',$data[$k]) : $data[$k],
                        'status' => $this -> auth -> isSuperAdmin() ? 300 : 100,
                        'info'  => $this -> auth -> isSuperAdmin() ? '管理员修改' : '申请提交',
                        'create_time' => time(),
                        'update_time'   => time()
                    ];
                }
            }
            if($logData){
                Db::name('centralcontactlog') -> insertAll($logData);
            }
            if($updateData){
                if(!$this -> auth -> isSuperAdmin()){
                    $updateData['status'] = 100;
                }

                $ret = $row -> save($updateData);
            }

            // 插入接洽记录
//            if(isset($data['record'])){
//                $recordData = [
//                    'centraloffice_id'  => $data['centraloffice_id'],
//                    'centralcontact_id' => $row -> id,
//                    'leader_ids'        => $row -> leader_ids,
//                    'centralcontact_name'   => $row -> name,
//                    'receive_time'  => strtotime($data['receive_time']),
//                    'is_new'        => $data['is_new']
//                ];
//                (new \app\admin\model\Centralcontactrecords()) -> save($recordData);
//            }
            $this -> success();
        }

        $progress_list = (new CentralcontactProgress()) -> where(['centralcontact_name' => $row -> name]) -> order('progress_time desc') -> select();
        $this -> assign('progress_list',$progress_list);

        $this -> assign('records',\app\admin\model\Centralcontact::all(['name' => $row -> name]));
        $this -> assign('centraloffices',getSelectList('centraloffice'));
        $this -> assign('streets',['-100'=>'待定']+getSelectList('chargedep',['group_id' => 5]));
        $this -> assign('leaders',getSelectList('leader')+['-100' => '无']);
        $this -> assign('chargeDeps',['-100'=>'待定']+$chargeDeps);
        $this -> assign('row',$row);
        return $this->view->fetch();
    }

    public function checkedit($ids = null){
        if(!$ids) $this -> error('请重试');
        $row = $this -> model -> find($ids);

        $chargeDepsArr = \app\admin\model\Chargedep::all();
        $chargeDeps = [];
        foreach ($chargeDepsArr as $dep){
            $chargeDeps[$dep -> id] = $dep -> name;
        }

        $list = $this -> model -> where('name',$row->name) -> select();

        $progress = (new CentralcontactProgress) -> where(['centralcontact_name'=>$row->name,'is_tmp'=>1]) -> select();

        $this -> assign('progress',$progress);
        $this -> assign('list',$list);
        $this -> assign('centraloffices',getSelectList('centraloffice'));
        $this -> assign('streets',getSelectList('chargedep',['group_id' => 5]));
        $this -> assign('leaders',getSelectList('leader'));
        $this -> assign('chargeDeps',['-100'=>'待定']+$chargeDeps);
        $this -> assign('row',$row);
        return $this -> fetch();
    }

    public function checkpass($ids = null){
        if(!$ids || !$this -> auth -> isSuperAdmin()) $this -> error('请刷新重试，或者您不是管理员');
        $rows = $this ->model -> whereIn('id',$ids) -> select();
        return $this -> check($rows,'pass');
    }

    public function checkreject($ids = null){
        if(!$ids || !$this -> auth -> isSuperAdmin()) $this -> error('请刷新重试，或者您不是管理员');
        $rows = $this ->model -> whereIn('id',$ids) -> select();
        if($this -> request -> isPost()){
            return $this -> check($rows,'reject');
        }
        $this -> assign('ids',$ids);
        return $this -> fetch();
    }

    /**
     * 一键通过所有
     */
    public function passall(){
        $rows = $this -> model -> where(['status' => 100]) -> select();
        if(!$rows){
            $this -> error('暂无需要审核的项目');
        }
        return $this -> check($rows,'pass');
    }

    private function check($rows = null, $action = null){
        if(!$rows || !$action) $this -> error('请刷新重试');


        $ret = true;
        foreach ($rows as $row){
            if('pass' == $action){
                foreach ($this->tmpFields as $tmpField) {
                    if($row -> $tmpField){
                        $field = $this -> ltrim($tmpField);
                        $row -> $field = $row -> $tmpField;
                        if($field == 'receive_time')
                            $row['receive_time_desc'] = date("Y-m-d",$row->tmp_receive_time);
                        $row -> $tmpField = null;
                    }
                }
                $row -> status = 0; // 通过
                $row -> reject_reason = '';

                Db::name('centralcontactlog') -> where(['status' => 100,'centralcontact_id' => $row -> id]) -> update(['status' => 300]);
                //审核进展
                Db::name('Centralcontact_progress') -> where(['centralcontact_name'=>$row->name,'is_tmp'=>1]) -> update(['is_tmp'=>0]);
            }else{
                $row -> reject_reason = $this -> request -> post('reject_reason');
                $row -> status = 200; // 驳回
                Db::name('centralcontactlog') -> where(['status' => 100,'centralcontact_id' => $row -> id]) -> update(['status' => 200]);
            }
            $ret = $row -> save();
        }
        if($ret !== false){
            $this -> success('成功');
        }
    }

    private function ltrim($tmpField){
        if(substr($tmpField,0,4) == 'tmp_'){
            return substr($tmpField,4);
        }
    }


    public  function import() {

        if($this->request->isPost()){
            $file = $this->request->request('filepath');
            $filePath = ROOT_PATH . DS . 'public' . DS . $file;
            if (!is_file($filePath)) {
                $this->error(__('No results were found'));
            }
            //实例化reader
            $ext = pathinfo($filePath, PATHINFO_EXTENSION);
            if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
                $this->error(__('Unknown data format'));
            }
            if ($ext === 'csv') {
                $file = fopen($filePath, 'r');
                $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
                $fp = fopen($filePath, "w");
                $n = 0;
                while ($line = fgets($file)) {
                    $line = rtrim($line, "\n\r\0");
                    $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                    if ($encoding != 'utf-8') {
                        $line = mb_convert_encoding($line, 'utf-8', $encoding);
                    }
                    if ($n == 0 || preg_match('/^".*"$/', $line)) {
                        fwrite($fp, $line . "\n");
                    } else {
                        fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                    }
                    $n++;
                }
                fclose($file) || fclose($fp);

                $reader = new Csv();
            } elseif ($ext === 'xls') {
                $reader = new Xls();
            } else {
                $reader = new Xlsx();
            }

            //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
            $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

            $table = $this->model->getQuery()->getTable();
            $database = \think\Config::get('database.database');
            $fieldArr = [];
            $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
            foreach ($list as $k => $v) {
                $fieldArr[] = $v['COLUMN_NAME'];
                // if ($importHeadType == 'comment') {
                //     $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
                // } else {
                //     $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
                // }
            }
            // pr($fieldArr);

            $insert = [];

            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            // $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $allRow = min($allRow, 200);
            // $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            // echo  $maxColumnNumber;

            $maxColumnNumber = 15;
            $startrow = 8;
            $fields = [];
            for ($currentRow = $startrow; $currentRow <= $startrow; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    // if($val)
                    if(!$this->auth->isSuperAdmin())
                    {
                        $val = 'tmp_'.$val;
                    }
                    $fields[] = $val;
                }
            }

            $msg = '';
            $errors = [];
            $addDataAll = [];
            $logDataAll = [];

//            $centraloffice_id = getSelectList('centraloffice');
//            $leader_ids = getSelectList('leader');
//            $settle_street_ids = getSelectList('chargedep',['group_id' => 5]);
//            $chargeDepsArr = \app\admin\model\Chargedep::all();
//            $chargeDeps = [];
//            foreach ($chargeDepsArr as $dep){
//                $chargeDeps[$dep -> id] = $dep -> name;
//            }
//            $chargedep_ids = ['-100'=>'待定']+$chargeDeps;


            for ($currentRow = $startrow+1; $currentRow <= $allRow; $currentRow++) {
                $error = '';
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_object($val) ? $val->__toString() : ($val == null ? '' : trim($val));
                }

                $temp = array_combine($fields, $values);

                if((isset($temp['name']) && $temp['name'] == '') && (isset($temp['tmp_name']) && $temp['tmp_name'] == '')){
                    $error .='项目名称必填<br>';
                }

                $res = [];
                foreach ($temp as $k => $v) {
                    if (in_array($k,$fieldArr) && $k !== '') {
                        $res[$k] = $v;
                    }

//                    if($k == 'chargedep_ids' || $k == 'settle_street_ids' || $k == 'leader_ids' || $k == 'centraloffice_id'){
//                        $res[$k] = array_flip(array_intersect($$k,explode(',',$res[$k])));
//                    }
                }

                $addData = $this->checkfileds($res,'centralcontact');

                if(!$this->auth->isSuperAdmin()) {
                    $addData['status'] = 100;
                } else{
                    $addData['status'] = 0;
                }



                if($error =='') {
                    $addDataAll[] = $addData;
                } else{
                    $errors[] = $addData['name'].":<br>".$error;
                }
            }

            $results =$this->model->allowField(true)->saveAll($addDataAll);

             if($results === false)
                 $this->error('数据保存错误');
             $this->success('所有项目导入成功');
            exit();
        }
        $expurl = url('exptpl');
        $this->assign('expurl', $expurl);
        return $this->view->fetch();
    }

    public function exptpl(){
        $error_msg ='';

        $save_name = '';
        $file_name = ROOT_PATH.'public/template/millionproject.xlsx';


        if (! file_exists ( $file_name )) {
            header('HTTP/1.1 404 NOT FOUND');
        } else {
            $filesize = filesize($file_name);
            header("Content-type: application/vnd.ms-excel");
            header("Content-Type: application/force-download");
            header('Content-Disposition: attachment;filename="'.$save_name.'.xlsx"');
            header( "Content-Length: ".$filesize);
            $data = file_get_contents($file_name);
            echo $data;
        }
    }

    /**
     * 查看详情
     */
    public function detail($ids = null){
        if(!$ids){
            $this -> error('请刷新重试');
        }

        $row = $this -> model ->find($ids);

        $records_list = \app\admin\model\Centralcontact::where(['name' => $row -> name])-> order('receive_time')->select();
        $progress_list = (new CentralcontactProgress()) -> where(['centralcontact_name' => $row -> name]) -> order('progress_time desc') -> select();

        $this -> assign('progress_list',$progress_list);
        $this -> assign('is_norecords',$this -> request -> param('is_norecords',0));
        $this -> assign('records',$records_list);
        $this -> assign('row',$row);
        return $this -> fetch();
    }


    public function checkfileds($params,$table_name) {
        // pr($params);
        // pr($this->fiveindustryArr);
        $fields_list = Db::name('fields')->where('table_name',$table_name)->select();
        // $data = [];
        foreach ($fields_list as $key => $value) {

            if($this->auth->isSuperAdmin())
                $field = $value['item_id'];
            else
                $field = 'tmp_'.$value['item_id'];

            if(!isset($params[$field]) )
                continue;

            if($params[$field] == '')
            {
                unset($params[$field]);
                continue;
                // $params[$field] = null;
            }


            if($value['item_type'] == "select")
            {
                $name_field = str_replace('id','name', $field);
                $name_field_value = $params[$field];


                if($params[$field] == PENDING_TEXT)
                {
                    $params[$name_field] = $name_field_value;
                    $params[$field] = PENDING;
                }
                else
                {
                    $params[$field] = preg_replace('/[^\x{4e00}-\x{9fa5}a-zA-Z0-9]/u',",",$params[$field]);
                    $rule = json_decode($value['item_rule'], true);


                    // echo $params[$field];
                    $name_value = explode(",",$params[$field]);
                    if(is_string($rule['datasource'])){
                        $tb_name = $rule['datasource'];
                        $params[$field] =  getSelectId($tb_name,$name_value);

                    }else
                        $params[$field] = array_search($params[$field], $rule['datasource']);

                    $params[$name_field] = $name_field_value;

                }

                // pr($params);


            }

            if($value['item_id'] == 'leader_ids'){
                if($params[$name_field] == '无'){
                    $params[$field] = '-100';
                }
            }
//            pr($params);
            if($value['item_type'] == "price")
            {
                if($params[$field] == PENDING_TEXT)
                    $params[$field] = PENDING;
                if($params[$field] == ZERO )
                {
                    unset($params[$field]);
                    continue;
                }
            }
            if($value['item_type'] == "datetime" || $value['item_type'] == "date")
            {
                // var_dump($params[$field]);

                if($params[$field] == PENDING_TEXT)
                {
                    $params[$field.'_desc'] = PENDING_TEXT;
                    $params[$field] = PENDING;
                }
                else
                {
                    $params[$field.'_desc'] = dateFormatter($params[$field],1);
                    $params[$field] = dateFormatter($params[$field]);
                }
            }

            if($value['item_type'] == 'radio')
            {
                if($params[$field] == '是')
                    $params[$field] = '1';
                elseif($params[$field] == '否')
                    $params[$field] = '1';
                else{
                    unset($params[$field]);
                    continue;
                }

            }

        }
        return $params;

    }

    public function insertdata(){
        $list = Db::table('sheet1')
            -> select();

        $data = [];
        foreach ($list as $v){


            $streets = $v['settle_street_ids'] ? (new \app\admin\model\Chargedep())->whereIn('name', explode(',',$v['settle_street_ids']))->value('GROUP_CONCAT(id)'):'-100';

            $signTime = $signtimestamp = null;
            if($v['sign_time']){
                $signtimestamp = strtotime(str_replace('.','-',trim($v['sign_time'])));
                $signTime = str_replace('.','-',trim($v['sign_time']));
            }


            $d = [
                'name'  => $v['name'],
                'investment_total'  => $v['investment_total'],
                'summary'   => $v['summary'],
                'progression'   => $v['progression'],
                'next_measure'  => $v['next_measure'],
                'problem'       => $v['problem'],
                'sign_time'     => $signtimestamp,
                'sign_time_desc' => $signTime,
                'settle_street_ids' => $streets,
                'settle_street_names'   => $v['settle_street_ids'] ?? '待定',
                'leader_ids'    => 4,
                'leader_names'  => '王波',
                'create_time'   => \time(),
                'update_time'   => \time()
            ];

            $data[] = $d;
        }

        pr($data);

        $this -> model -> insertAll($data);
    }


    /**
     * 删除
     */
    public function singledel($ids = "")
    {
        if ($ids) {
            // $row = $this -> model ->find($ids);
            // $count = \app\admin\model\Centralcontact::where(['name' => $row -> name])-> count();
            // if ($count>1){

            // }else{
            //     $this->error(__('不支持编辑内部删除，请在列表中删除！'));
            // }
            $list = $this->model->where('id', $ids)->delete();
            if ($list) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }

        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    public function del($ids = null ){
        $ids = $ids ? $ids : $this->request->param("ids");
        $row = $this -> model -> find($ids);
        if(!$row)
            $this->error('记录不存在');
        $row->is_delete = 1;
        $row->save();
        $this->success();
    }

    public function export(){
        ini_set('memory_limit', '999M');
        $xlsName = '区双招双引中心接洽项目数据导出';
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        // 搜索条件
        // $filter = $this->request->get("filter");
        // $filter = (array)json_decode($filter, true);
        // //项目名称
        // if(isset($filter['name']))
        //     $this -> whereExtend['name'] = ['like','%'.$filter['name'].'%'];
        // //投资方地区
        // if(isset($filter['investment_area']))
        //     $this -> whereExtend['investment_area'] = ['like','%'.$filter['investment_area'].'%'];
        // //责任单位
        // if(isset($filter['chargedep_names']))
        //     $this -> whereExtend['chargedep_names'] = ['like','%'.$filter['chargedep_names'].'%'];
        // //落户街道
        // if(isset($filter['settle_street_names']))
        //     $this -> whereExtend['settle_street_names'] = ['like','%'.$filter['settle_street_names'].'%'];

        // //接洽时间
        // if(isset($filter['receive_time']))
        // {
        //     $receive_time = $filter['receive_time'];
        //     $dispatchTimeArr = explode(' - ',$wlastmen_time);
        //     $dispatchtimeBetween = [strtotime(trim($dispatchTimeArr[0])),strtotime(trim($dispatchTimeArr[1]))];
        //     $this -> whereExtend[
        //         'receive_time'
        //     ] = ['between',$dispatchtimeBetween];
        // }
        // //参与区领导
        // if(isset($filter['leader_names']))
        //     $this -> whereExtend['leader_names'] = ['like','%'.$filter['leader_names'].'%'];
        // //责任科室
        // if(isset($filter['centraloffice_name']))
        //     $this -> whereExtend['centraloffice_name'] = ['like','%'.$filter['centraloffice_name'].'%'];
        // list($where, $sort, $order, $offset, $limit) = $this->buildparams();

        // if(input('leader_id')){
        //     $this->whereExtend[] = ['exp',Db::raw("FIND_IN_SET(".input('leader_id').",leader_ids)")];
        // }

        if(input('ids')){
            $this -> whereExtend['id'] = ['in',input('ids')];
        }

        if(input('leader_id')){
            $admin_id = input('leader_id');
            $this->whereExtend[] = ['exp',Db::raw("FIND_IN_SET($admin_id,leader_ids)")];
        }
        // 已审核
        $this->whereExtend['status'] = 0;
        $res =  $this->model->where($where)
                ->where($this->whereExtend)-> order('receive_time desc')->select();
        $lastestcentral = $this->getlastestcentral();
        $lastestprogress = $this->getlastestprogress();
        $list = [];
        foreach ($res as $key => $value) {
            $name = $value['name'];
            $list[$name] =$lastestcentral[$name];
            if(isset($lastestprogress[$name]['content']) && $lastestprogress[$name]['content'])
                $list[$name]['progression'] = $lastestprogress[$name]['content'];
            if(isset($lastestprogress[$name]['problem']) && $lastestprogress[$name]['problem'])
                $list[$name]['problem'] = $lastestprogress[$name]['problem'];
            if(isset($lastestprogress[$name]['next_measure']) &&  $lastestprogress[$name]['next_measure'])
                $list[$name]['next_measure'] = $lastestprogress[$name]['next_measure'];
        }

        $project_state = array('终止','暂停','在谈','框架','正式','注册','开工','运营');
        $stop = [];
        $suspend = [];
        $discuss = [];
        $frame = [];
        $formal = [];
        $register = [];
        $start = [];
        $operate = [];
        //数组拆分
        foreach($list as $key => $v)
        {
            if($v['state']==$project_state[0])
                $stop[$key] = $v->toArray();
            if($v['state']==$project_state[1])
                $suspend[$key] = $v->toArray();           
            if($v['state']==$project_state[2])
                $discuss[$key] = $v->toArray();
            if($v['state']==$project_state[3])
                $frame[$key] = $v->toArray();
            if($v['state']==$project_state[4])
                $formal[$key] = $v->toArray();
            if($v['state']==$project_state[5])
                $register[$key] = $v->toArray(); 
            if($v['state']==$project_state[6])
                $start[$key] = $v->toArray();  
            if($v['state']==$project_state[7])
                $operate[$key] = $v->toArray();  
        }
        // 数组合并
        $lists = array_merge($stop,$suspend,$discuss,$frame,$formal,$register,$start,$operate);
        
        // pr($list);
//         foreach ($list as &$item){
//             $item['progress_content'] = $progressArr[$item['name']] ?? '';
//         }

//         $tmpSql = Db::name('centralcontact')
//             -> order('receive_time desc')
//             ->where(['name',['in',$nameArr]])
//             // ->where($this->whereExtend)
//             ->limit(999999) // 不加limit不生效
//             -> buildSql();
//         $tmp = \db() -> table($tmpSql . " a")
// //                ->where($where)
// //                ->where($this->whereExtend)
// //                ->limit($offset, $limit)  //取消掉limit，获取所有的记录
//             ->order($this->sortExtend)
//             ->order($sort, $order)
//             ->group('a.name')
//             ->column('id');


//         $list = $this->model
//             ->with($this->relationtTable)
//             ->whereIn('id',$tmp)
//             // ->order('id','desc')
//             -> order('receive_time desc')
//             ->select();



//         $tmpSql2 = Db::name('centralcontact_progress')
//             -> where(['is_tmp'=>0])
//             -> order('progress_time desc')
//             ->limit(9999999) // 不加limit不生效
//             -> buildSql();
//         $tmp2 = \db() -> table($tmpSql2 . " a")
//             ->group('a.centralcontact_name')
//             ->column('id,centralcontact_name,content');

//         $progressArr = [];
//         foreach ($tmp2 as $k => $v){
//             $progressArr[$v['centralcontact_name']] = $v['content'];
//         }


        $xlsDataReal = [];
        $xlsCell = array('序号','项目名称','总投资(亿元)','项目简介','计划准入时间','投资方地区','责任单位','落户街道','参与区领导','责任科室','科室责任人','接洽时间','项目状态','项目状态时间','终止原因','进展详情','存在问题','下一步措施');
        $i=0;
        foreach ($lists as $key => $value) {
            $xlsDataReal[] = [
                ++$i,
                $value['name'],
                $value['investment_total'],
                $value['summary'],
                $value['access_time_text'],
                // $value['sign_time_text'],
                $value['investment_area'],
                $value['chargedep_names'],
                $value['settle_street_names'],
                $value['leader_names'],
                $value['centraloffice_name'],
                $value['contact_name'],
                $value['receive_time_text'],
                $value['state'],
                $value['current_state_time_text'],
                $value['state'] == '终止' ? $value['stop_reason'] : '',
                $value['progression'],
                $value['problem'],
                $value['next_measure']
            ];
        }
        exportExcel($xlsName,'Excel2007', $xlsDataReal, $xlsCell);
    }

    public function addprogress($ids = null){
        $row = $this -> model -> get($ids);
        if($this->request->isPost()){
            $data = $this -> request -> post('row/a');
            $ret = (new CentralcontactProgress()) -> save($data);
            if($ret){
                $row->status = 100;
                $row->save();
                $this -> success('成功');
            }
        }

        $this -> assign('row',$row);
        return $this -> fetch();
    }


    public function editprogress($ids)
    {
        $row = (new CentralcontactProgress()) -> get($ids);

        if(!$row)
            $this->error('记录不存在');
        $central_row = $this->model->where('name',$row['centralcontact_name'])->order('receive_time','desc')->find();
        if($this->request->isPost()){
            $data = $this -> request -> post('row/a');
            $data['is_tmp'] = 1;
            $ret = $row -> save($data);
            if($ret){
                $central_row->status = 100;
                $central_row->save();
                $this -> success('成功');
            }
        }

        $this -> assign('row',$row);
        return $this -> fetch();
    }
    /**
     * 删除
     */
    public function delprogress($ids = "")
    {
        if ($ids) {
            $row = (new CentralcontactProgress()) -> get($ids);
            $res = $row->delete();
            if ($res) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }


    public function getlastestprogress(){
        $tmpSql2 = Db::name('centralcontact_progress')
            -> where(['is_tmp'=>0])
            -> order('progress_time desc')
            ->limit(9999999) // 不加limit不生效
            -> buildSql();
        $tmp2 = \db() -> table($tmpSql2 . " a")
            ->group('a.centralcontact_name')
            ->column('id');


        $res = (new CentralcontactProgress())
            ->whereIn('id',$tmp2)
            ->select();
        $list = [];
        foreach ($res as $key => $value) {
            $list[$value['centralcontact_name']] = $value;
        }

        return $list;
        // return $tmp2;
    }
     public function lastestprogress(){
        $tmpSql2 = Db::name('centralcontact_progress')
            -> where(['is_tmp'=>0])
            -> order('progress_time desc')
            ->limit(9999999) // 不加limit不生效
            -> buildSql();
        echo $tmpSql2;
        $tmp2 = \db() -> table($tmpSql2 . " a")
            ->group('a.centralcontact_name')
            ->column('id');


        $res = (new CentralcontactProgress())
            ->whereIn('id',$tmp2)
            ->select();
        $list = [];
        foreach ($res as $key => $value) {
            $list[$value['centralcontact_name']] = $value;
        }
        pr(collection($list)->toArray());
        // return $list;
        // return $tmp2;
    }
    public function getlastestcentral() {
        $tmpSql = Db::name('centralcontact')
            -> order('receive_time desc')

            // ->where($this->whereExtend)
            ->limit(999999) // 不加limit不生效
            -> buildSql();
        $tmp = \db() -> table($tmpSql . " a")
//                ->where($where)
//                ->where($this->whereExtend)
//                ->limit($offset, $limit)  //取消掉limit，获取所有的记录

            ->group('a.name')
            ->column('id');


        $res = $this->model
            ->whereIn('id',$tmp)
            ->select();
        // $list = $this->model
        //     ->whereIn('id',$tmp)
        //     // ->order('id','desc')

        //     ->select();
        $list = [];
        foreach ($res as $key => $value) {
            $list[$value['name']] = $value;
        }
        return $list;
    }

    public function test() {
         $tmpSql2 = Db::name('centralcontact_progress')
            -> where(['is_tmp'=>0])
            -> order('progress_time desc')
            ->limit(9999999) // 不加limit不生效
            -> buildSql();
        $tmp2 = \db() -> table($tmpSql2 . " a")
            ->group('a.centralcontact_name')
            ->column('id');


        $res = (new CentralcontactProgress())
            ->whereIn('id',$tmp2)
            ->select();
        $list = [];
        foreach ($res as $key => $value) {
            $list[$value['centralcontact_name']] = $value;
        }

        pr(collection($list)->toArray());
    }


    protected function buildtablewhere($searchfields = null, $relationSearch = null)
    {
        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
        $order = $this->request->get("order", "DESC");
        $offset = $this->request->get("offset", 0);
        $limit = $this->request->get("limit", 0);
        $filter = (array)json_decode($filter, true);
        $op = (array)json_decode($op, true);
        $filter = $filter ? $filter : [];
        $where = [];
        $tableName = '';
        if ($relationSearch) {
            if (!empty($this->model)) {
                $name = \think\Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
                $name = $this->model->getTable();
                $tableName = $name . '.';
            }
            $sortArr = explode(',', $sort);
            foreach ($sortArr as $index => & $item) {
                $item = stripos($item, ".") === false ? $tableName . trim($item) : $item;
            }
            unset($item);
            $sort = implode(',', $sortArr);
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $where[] = [$tableName . $this->dataLimitField, 'in', $adminIds];
        }
        if ($search) {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v) {
                $v = stripos($v, ".") === false ? $tableName . $v : $v;
            }
            unset($v);
            $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
        }
        foreach ($filter as $k => $v) {
            $sym = isset($op[$k]) ? $op[$k] : '=';
            if (stripos($k, ".") === false) {
                $k = $tableName . $k;
            }
            $v = !is_array($v) ? trim($v) : $v;
            $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
            switch ($sym) {
                case '=':
                case '<>':
                    $where[] = [$k, $sym, (string)$v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FINDINSET':
                case 'FIND_IN_SET':
                    $where[] = "FIND_IN_SET('{$v}', " . ($relationSearch ? $k : '`' . str_replace('.', '`.`', $k) . '`') . ")";
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    foreach ($arr as $key => &$value) {
                        $value = strtotime($value);
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = strtotime($arr[1]);
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = strtotime($arr[0]);
                    }

                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' time', $arr];
                    break;
                case 'LIKE':
                case 'LIKE %...%':
                    $where[] = [$k, 'LIKE', "%{$v}%"];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
        }
        $where = function ($query) use ($where) {
            foreach ($where as $k => $v) {
                if (is_array($v)) {
                    call_user_func_array([$query, 'where'], $v);
                } else {
                    $query->where($v);
                }
            }
        };
        return [$where];

    }

}













